// pages/result/result.js
const app = getApp();
const X_AUTH_KEY = '50871805b4160a5f51b44b235e4f3c8eda33cebcb03f985544db72f3a1dac6ba';
const API_BASE_URL = 'https://iw6i1vjj93ml.guyubao.com';

Page({
  data: {
    activeTab: 'overview',
    pageData: null,
    transcript: '',
    isTranscriptLoaded: false,
    isTranscriptLoading: false, // 增加此状态用于防止重复触发
  },

  onLoad(options) {
    if (options && options.data) {
      try {
        const serverData = JSON.parse(decodeURIComponent(options.data));
        this.setData({
          pageData: this.adaptServerData(serverData)
        });
      } catch (e) {
        console.error("解析或适配服务器数据失败:", e);
        wx.showToast({ title: '数据加载失败', icon: 'none' });
      }
    } else {
      console.error("结果页未收到任何数据");
      wx.navigateBack();
    }
  },

  switchTab(e) {
    const newTab = e.currentTarget.dataset.tab;
    if (newTab === this.data.activeTab) return;
    
    this.setData({ activeTab: newTab });

    if (newTab === 'transcript' && !this.data.isTranscriptLoaded && !this.data.isTranscriptLoading) {
      this.handleExtractTranscript();
    }
  },

  async handleExtractTranscript() {
    this.setData({ isTranscriptLoading: true });
    wx.showLoading({ title: '正在提交任务...', mask: true });

    try {
      const token = wx.getStorageSync('token');
      const headers = {
        'Authorization': 'Bearer ' + token,
        'x-source': 'wechat_mini_video_get',
        'X-Auth-Key': X_AUTH_KEY
      };

      const submitRes = await app.wxRequestPromise({
        baseURL: API_BASE_URL,
        url: '/api/media/extract/sd',
        method: 'POST',
        header: headers,
        data: {
          url: this.data.pageData.original_url,
          extract_text: true,
          include_comments: false
        }
      });

      if (submitRes && submitRes.code === 202 && submitRes.task_id) {
        const pollingHeaders = { ...headers, 'x-root-trace-key': submitRes.root_trace_key };
        await this.pollForResult(submitRes.task_id, pollingHeaders);
      } else if (submitRes && submitRes.code === 200 && submitRes.data) {
        this.processSuccessData(submitRes.data);
      } else {
        throw new Error(submitRes.message || '提交任务失败');
      }
    } catch (error) {
      this.setData({ isTranscriptLoading: false }); // 失败时重置状态
      wx.hideLoading();
      wx.showToast({ title: error.message, icon: 'none' });
    }
  },

  async pollForResult(taskId, headers) {
    const maxAttempts = 30;
    const pollInterval = 10000;

    try {
      for (let i = 0; i < maxAttempts; i++) {
        const progress = Math.round(((i + 1) / maxAttempts) * 100);
        wx.showLoading({ title: `提取中...${progress}%`, mask: true });

        const statusRes = await app.wxRequestPromise({
          baseURL: API_BASE_URL,
          url: `/api/media/extract/wxmn/status/${taskId}`,
          method: 'GET',
          header: headers
        });

        if (statusRes.code === 200 && statusRes.status === 'completed') {
          this.processSuccessData(statusRes.data);
          return;
        } else if (statusRes.status === 'failed') {
          throw new Error(statusRes.message || '任务处理失败');
        }
        
        await new Promise(resolve => setTimeout(resolve, pollInterval));
      }
      throw new Error('无法在规定时间内获取文案');
    } finally {
      wx.hideLoading();
    }
  },
  
  processSuccessData(data) {
    const content = data.content || data.description || '未提取到有效文案';
    this.setData({
      transcript: content,
      isTranscriptLoaded: true,
      isTranscriptLoading: false,
    });
    wx.showToast({ title: '文案提取成功', icon: 'success' });
  },

  exportVideo() {
    const videoUrl = this.data.pageData?.media.videoUrl;
    if (!videoUrl) {
      wx.showToast({ title: '无视频可导出', icon: 'none' });
      return;
    }
    wx.showLoading({ title: '准备下载中...' });
    wx.downloadFile({
      url: videoUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          wx.saveVideoToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => wx.showToast({ title: '已保存到相册', icon: 'success' }),
            fail: (err) => wx.showToast({ title: err.errMsg.includes('auth deny') ? '您已拒绝授权' : '保存失败', icon: 'none' })
          });
        } else {
          wx.showToast({ title: '下载失败', icon: 'none' });
        }
      },
      fail: (err) => wx.showToast({ title: '下载链接出错', icon: 'none' }),
      complete: () => wx.hideLoading()
    });
  },
  
  copyTranscript() {
    if (!this.data.isTranscriptLoaded) return;
    wx.setClipboardData({
      data: this.data.transcript,
      success: () => wx.showToast({ title: '文案已复制' })
    });
  },

  addToFavorites() { wx.showToast({ title: '收藏功能待开发', icon: 'none' }); },

  adaptServerData(serverData) {
    const originalVideoUrl = serverData.media?.video_url;
    let proxiedVideoUrl = '';
    if (originalVideoUrl) {
      proxiedVideoUrl = `${API_BASE_URL}/api/media/proxy/vd?url=${encodeURIComponent(originalVideoUrl)}`;
    }
    const pageData = {
      original_url: serverData.original_url,
      title: serverData.title || '无标题',
      description: serverData.description || serverData.title || '无文案信息',
      publish_time: serverData.publish_time ? new Date(serverData.publish_time).toLocaleString('zh-CN', { dateStyle: 'medium', timeStyle: 'short' }) : '未知时间',
      tags: serverData.tags || [],
      author: {
        nickname: serverData.author?.nickname || '未知作者',
        avatar: serverData.author?.avatar || '/assets/images/default-avatar.png'
      },
      media: {
        videoUrl: proxiedVideoUrl,
        duration: this.formatDuration(serverData.media?.duration || 0)
      },
      statistics: {
        like_count: this.formatCount(serverData.statistics?.like_count),
        comment_count: this.formatCount(serverData.statistics?.comment_count),
        share_count: this.formatCount(serverData.statistics?.share_count),
        collect_count: this.formatCount(serverData.statistics?.collect_count),
      }
    };
    return pageData;
  },
  
  formatDuration(seconds = 0) {
    const min = Math.floor(seconds / 60).toString().padStart(2, '0');
    const sec = Math.floor(seconds % 60).toString().padStart(2, '0');
    return `${min}:${sec}`;
  },

  formatCount(count) {
    if (typeof count !== 'number' || count < 0) return 0;
    if (count < 10000) return count;
    return (count / 10000).toFixed(1) + 'w';
  }
});